package com.example.netty.netty.codec;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

import java.util.concurrent.TimeUnit;

//需要继承一个HandlerAdapter（有很多个）
public class NettyServerHandler extends ChannelInboundHandlerAdapter {
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        //也可以使用SimpleChannelInboundHandler<StudentPOJO.Student>指定消息类型，就不用强转了
        StudentPOJO.Student student = (StudentPOJO.Student) msg;
        System.out.println(student.getId()+" "+ student.getName());
    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        //读取完成后触发，一般用于数据返回
        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,client...",CharsetUtil.UTF_8));
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        //发生异常时触发，一般要关闭通道
        ctx.close();
    }
}
